import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { characterAnalysis, getCharacterDetail } from '../../services/character';
import { createOrder, payOrder } from '../../services/payment';
import useAuthStore from '../../store/auth';
import usePaymentStore from '../../store/payment';

const CharacterAnalysis: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const baziId = location.state?.baziId;
  
  const [characterData, setCharacterData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [showPayment, setShowPayment] = useState(false);
  const [paymentLoading, setPaymentLoading] = useState(false);
  
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  const updateBalance = usePaymentStore(state => state.updateBalance);
  const setPendingOrder = usePaymentStore(state => state.setPendingOrder);
  
  useEffect(() => {
    if (!baziId) {
      setError('请先进行八字分析');
      return;
    }
    
    fetchCharacterAnalysis();
  }, [baziId]);
  
  const fetchCharacterAnalysis = async () => {
    try {
      setLoading(true);
      setError('');
      
      // 调用性格分析API
      const response = await characterAnalysis({ baziId });
      
      if (response.code === 200) {
        setCharacterData(response.data);
        setShowPayment(!response.data.isPaid);
      } else if (response.code === 403) {
        // 需要付费
        setCharacterData(response.data);
        setShowPayment(true);
      } else {
        setError(response.message || '性格分析失败');
      }
    } catch (err: any) {
      setError(err.message || '性格分析失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  const handlePayment = async () => {
    if (!isAuthenticated) {
      // 未登录，跳转到登录页
      navigate('/login');
      return;
    }
    
    try {
      setPaymentLoading(true);
      
      // 创建订单
      const orderResponse = await createOrder({
        productType: 'character_detail',
        productId: characterData.characterId,
        amount: isAuthenticated ? 0.1 : 1.1
      });
      
      if (orderResponse.code !== 200) {
        throw new Error(orderResponse.message || '创建订单失败');
      }
      
      // 支付订单
      const payResponse = await payOrder({
        orderNo: orderResponse.data.orderNo,
        paymentType: 'wallet'
      });
      
      if (payResponse.code === 200) {
        // 支付成功，更新钱包余额
        updateBalance(payResponse.data.balance);
        
        // 重新获取性格详情
        const detailResponse = await getCharacterDetail(characterData.characterId);
        if (detailResponse.code === 200) {
          setCharacterData(detailResponse.data);
          setShowPayment(false);
        }
      } else {
        throw new Error(payResponse.message || '支付失败');
      }
    } catch (err: any) {
      setError(err.message || '支付失败，请稍后再试');
      
      // 如果是余额不足，跳转到钱包充值页面
      if (err.message.includes('余额不足')) {
        setPendingOrder({
          orderNo: null,
          amount: isAuthenticated ? 0.1 : 1.1,
          productType: 'character_detail',
          productId: characterData.characterId
        });
        navigate('/wallet');
      }
    } finally {
      setPaymentLoading(false);
    }
  };
  
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
      </div>
    );
  }
  
  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <h3 className="text-lg font-medium text-red-500">{error}</h3>
          <button
            onClick={() => navigate('/bazi')}
            className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            进行八字分析
          </button>
        </div>
      </div>
    );
  }
  
  if (!characterData) {
    return null;
  }
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-3xl mx-auto bg-white rounded-xl shadow-md overflow-hidden">
        <div className="p-6">
          <h2 className="text-2xl font-bold text-gray-900 text-center mb-6">性格分析结果</h2>
          
          {/* 基本信息 */}
          <div className="bg-gray-50 p-4 rounded-lg mb-6">
            <h3 className="text-lg font-medium text-gray-900 mb-2">基本信息</h3>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <span className="text-gray-500">姓名：</span>
                <span>{characterData.name || '未提供'}</span>
              </div>
              <div>
                <span className="text-gray-500">性别：</span>
                <span>{characterData.gender === 1 ? '男' : '女'}</span>
              </div>
              <div>
                <span className="text-gray-500">出生日期：</span>
                <span>{characterData.birthYear}年{characterData.birthMonth}月{characterData.birthDay}日</span>
              </div>
              <div>
                <span className="text-gray-500">八字：</span>
                <span>{characterData.bazi}</span>
              </div>
            </div>
          </div>
          
          {/* 基础性格特点 */}
          <div className="mb-6">
            <h3 className="text-lg font-medium text-gray-900 mb-2">基础性格特点</h3>
            <div className="prose max-w-none">
              <p>{characterData.basicCharacter}</p>
            </div>
          </div>
          
          {/* 付费内容 */}
          {showPayment ? (
            <div className="bg-indigo-50 p-6 rounded-lg border border-indigo-100 text-center">
              <h3 className="text-lg font-medium text-indigo-900 mb-2">查看详细性格分析</h3>
              <p className="text-indigo-700 mb-4">
                详细分析包含性格优缺点、人际关系、工作特点、情感表达等全面解读
              </p>
              <button
                onClick={handlePayment}
                disabled={paymentLoading}
                className={`inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${paymentLoading ? 'opacity-70 cursor-not-allowed' : ''}`}
              >
                {paymentLoading ? '处理中...' : `支付${isAuthenticated ? '0.1' : '1.1'}元查看详情`}
              </button>
              <p className="mt-2 text-xs text-indigo-500">
                {isAuthenticated ? '已登录用户优惠价' : '登录后可享受优惠价格'}，VIP会员无限查看
              </p>
            </div>
          ) : (
            <div className="mb-6">
              <h3 className="text-lg font-medium text-gray-900 mb-2">详细性格分析</h3>
              <div className="prose max-w-none">
                <h4 className="text-md font-medium text-gray-800">性格优点</h4>
                <p>{characterData.detailCharacter?.strengths}</p>
                
                <h4 className="text-md font-medium text-gray-800 mt-4">性格缺点</h4>
                <p>{characterData.detailCharacter?.weaknesses}</p>
                
                <h4 className="text-md font-medium text-gray-800 mt-4">人际关系</h4>
                <p>{characterData.detailCharacter?.relationships}</p>
                
                <h4 className="text-md font-medium text-gray-800 mt-4">工作特点</h4>
                <p>{characterData.detailCharacter?.workStyle}</p>
                
                <h4 className="text-md font-medium text-gray-800 mt-4">情感表达</h4>
                <p>{characterData.detailCharacter?.emotionalExpression}</p>
                
                <h4 className="text-md font-medium text-gray-800 mt-4">适合职业</h4>
                <p>{characterData.detailCharacter?.suitableCareers}</p>
              </div>
            </div>
          )}
          
          {/* 操作按钮 */}
          <div className="mt-8 flex justify-center space-x-4">
            <button
              onClick={() => navigate(`/bazi/${baziId}`)}
              className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              返回八字分析
            </button>
            <button
              onClick={() => navigate(`/fortune/daily/${baziId}`)}
              className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              查看今日运势
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CharacterAnalysis;
